package com.zdya.combatdocuments.util;

import com.alibaba.fastjson.JSON;
import com.zdya.combatdocuments.entity.User;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AESUtils {

    /*
     * 后端PKCS5Padding补码方式和前端的CryptoJS.pad.Pkcs7效果一致
     * key的字符串长度限制为16
     * */
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";

    //加密
    public static String encrypt(String content, String key) {
        try {
            byte[] raw = key.getBytes();  //获得密码的字节数组
            SecretKeySpec skey = new SecretKeySpec(raw, "AES"); //根据密码生成AES密钥
            Cipher cipher = Cipher.getInstance(ALGORITHMSTR);  //根据指定算法ALGORITHM自成密码器
            cipher.init(Cipher.ENCRYPT_MODE, skey); //初始化密码器，第一个参数为加密(ENCRYPT_MODE)或者解密(DECRYPT_MODE)操作，第二个参数为生成的AES密钥
            byte[] byteContent = content.getBytes("utf-8"); //获取加密内容的字节数组(设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
            byte[] encodeContent = cipher.doFinal(byteContent); //密码器加密数据
            return Base64.getEncoder().encodeToString(encodeContent); //将加密后的数据转换为字符串返回
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //解密
    public static String decrypt(String encryptStr, String decryptKey) {
        try {
            byte[] raw = decryptKey.getBytes();  //获得密码的字节数组
            SecretKeySpec skey = new SecretKeySpec(raw, "AES"); //根据密码生成AES密钥
            Cipher cipher = Cipher.getInstance(ALGORITHMSTR);  //根据指定算法ALGORITHM自成密码器
            cipher.init(Cipher.DECRYPT_MODE, skey); //初始化密码器，第一个参数为加密(ENCRYPT_MODE)或者解密(DECRYPT_MODE)操作，第二个参数为生成的AES密钥
            byte[] encodeContent = Base64.getDecoder().decode(encryptStr); //把密文字符串转回密文字节数组
            byte[] byteContent = cipher.doFinal(encodeContent); //密码器解密数据
            return new String(byteContent, "utf-8"); //将解密后的数据转换为字符串返回
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        User userEntity = new User();
        userEntity.setId(1L);
        userEntity.setName("张三");
        userEntity.setUsername("123");
        userEntity.setPassword("123");
        String s = JSON.toJSONString(userEntity);
        String e = AESUtils.encrypt(s, "qwqw1234qwqw1234qwqw1234szqwqw12");
        System.out.println(e);
        System.out.println(AESUtils.decrypt(e, "qwqw1234qwqw1234qwqw1234szqwqw12"));
    }
}